import {Component, OnInit} from '@angular/core';
import {LocalDataSource} from 'ng2-smart-table';
import {SmartTableData} from '../../@core/data/smart-table';
import {ActivatedRoute} from "@angular/router";
import {CommonFormDialog} from "../../utils/CommonFormDialog";
import {NbDialogService} from "@nebular/theme";
import {AdminService} from "../../AdminService";
import {AdminInfo, AuthService} from "../../energy/api";
import {BaseRequest} from "../../utils/BaseRequest";

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './manage-admin.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
    button {
      margin-top: 5px;
      margin-bottom: 5px;
      margin-right: 10px;
    }

    .margin {
      margin: 10px;
    }
  `],
})
export class ManageAdminComponent implements OnInit{
  settings = {
    pager:{
      display:false,
    },
    hideSubHeader: true,
    actions: {
      add: false,
      columnTitle: '操作',
      position: 'right',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      adminId: {
        title: 'ID',
        type: 'number',
      },
      adminName: {
        title: '用户名',
        type: 'string',
      },
      adminPassword: {
        title: '密码',
        type: 'string',
      },
      teamName: {
        title: '团队名',
        type: 'string',
      },
      extInfo: {
        title: '额外信息',
        type: 'string',
      },
    },
  };
  source: LocalDataSource = new LocalDataSource();
  maxPage:number = 1;
  page:number = 1;
  limit:number = 25;
  adminName:string = '';
  teamName:string  = '';
  constructor(private service: SmartTableData
              ,private api:AuthService
              ,private route:ActivatedRoute
              , private dialogService: NbDialogService
              ,private admin:AdminService) {

  }
  ngOnInit(): void {
    this.goto(1);
  }

  openAddPrompt(){
    const keys = Object.keys(this.settings.columns).filter(k => {
      return (this.settings.columns[k]['type'] == 'string' || this.settings.columns[k]['type'] == 'number')
        && this.settings.columns[k]['title'] != 'ID' && k!='unitId' && k!='createDate'
    });
    const columns = keys.map(k => {
      return this.settings.columns[k];
    });
    this.dialogService.open(CommonFormDialog,{
      context:{
        data:columns,
        title: '新建管理员'
      }
    }).onClose.subscribe(results=>{
      const data = <AdminInfo>{};
      keys.forEach((k, i) => {
        if (columns[i]['type'] == 'number') {
          data[k] = Number(results[i]);
        } else {
          data[k] = results[i];
        }
      });
      data['operateType'] = "0";
      this.api.postECASyncAdmin(new BaseRequest([data])).toPromise().then(response => {
        console.log(response);
        this.goto(this.page);
      })
    })
  }

  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.api.postECASyncAdmin(new BaseRequest(
        [{
          operateType:"2",
          adminId:event.data['adminId'],
        }]
    )).toPromise().then(res=>{
        if(res.success){
          event.confirm.resolve();
        }else{
          event.confirm.reject();
        }
      }).catch(e=>{
        event.confirm.reject();
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }

  onEditConfirm(event):void {
    const newData = event.newData;
    newData['operateType']="1";
    this.api.postECASyncAdmin(new BaseRequest([newData])).toPromise().then(response=>{
      console.log(response);
      event.confirm.resolve();
    }).catch(e=>{
      console.log(e);
      event.confirm.reject();
    })
  }

  goto(page: number){
    this.page = page;
    const query = {
      pageIndex:(this.page-1)*this.limit,
      pageSize:this.limit,
    };
    if(this.adminName!='') query['adminName'] = this.adminName;
    if(this.teamName!='') query['teamName'] = this.teamName;
    this.api.requestECAAdmin(new BaseRequest(query)).toPromise().then(response=>{
      console.log(response);
      this.maxPage = Math.ceil(response.dataCount / this.limit);
      this.source.load(response.data);
    });
  }
}

